/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "Realmd/RealmList.h"
#include "Ucop/Macros.h"
#include "Ucop/System/LockGuard.h"
#include "Shared/Typedefs.h"
#include "Shared/Log/Log.h"
#include "Realmd/Global.h"
using Ucop::System::LockGuard;
using Ucop::System::Mutex;


RealmList::RealmList(void)
	: _Myrealms()
	, _MyrealmsLock()
{

}

RealmList::~RealmList(void)
{
	Clear();
}

void RealmList::Update(void)
{
	UCOP_LOCK_GURAD_ASSERT(_MyrealmsLock);

	_Myrealms.clear();
	QueryResultPtr _Result(sLoginDB.PQuery("SELECT * FROM realmlist;"));
	if (_Result.get())
	{
		do
		{
			struct Realm _Realm = { 0 };
			_Realm.Id = (*_Result)[0].AsUInt32();
			_Realm.Name = (*_Result)[1].AsString();
			_Realm.Address.append((*_Result)[2].c_str())
				.append(":").append((*_Result)[3].c_str());
			_Realm.Icon = (*_Result)[4].AsUInt8();
			_Realm.RealmFlags = (RealmFlags)(*_Result)[5].AsUInt8();
			_Realm.Timezone = (*_Result)[6].AsUInt8();
			_Realm.PopulationLevel = (*_Result)[8].AsFloat();
			_Myrealms.push_back(_Realm);
		} while (_Result->NextRow());
	}

	sLog.outDebug("Load %d realms from database", _Myrealms.size());
}

const RealmList::RealmArray RealmList::GetRealms(void)
{
	UCOP_LOCK_GURAD_ASSERT(_MyrealmsLock);
	return _Myrealms;
}

void RealmList::Clear(void)
{
	UCOP_LOCK_GURAD_ASSERT(_MyrealmsLock);
	_Myrealms.clear();
}